<script setup>
import { ref, onMounted } from "vue";
import "vditor/dist/index.css";
import Vditor from "vditor";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { insertBlog } from '@/api/blogs'
import { useRouter } from "vue-router";

const vditor = ref();
const token = ref('');
const router = useRouter();

const form = ref({
  user_id: "",
  title: "",
  image: "",
  content: "",
});

//提交表单
const onSubmit = async () => {
  const User = JSON.parse(localStorage.getItem("token"));
  form.value.user_id = User.id;
  form.value.content = vditor.value.getValue();
  const res = await insertBlog(form.value);
  if (res.code === 1) {
    ElMessage.success(res.msg);
  }else{
    ElMessage.error(res.msg)
  }
  localStorage.removeItem("vditorvditor");
  router.push("/myblogs");
};

//重置表单
const cancel = () => {
  
}

onMounted(async () => {
  getToken();

  
  vditor.value = new Vditor("vditor", {
    height: "80vh",
    width: "100%",
    after: () => {
      vditor.value.setValue("请输入内容");
    },
    // 上传图片
    upload: {
      accept: "image/*", // 图片类型
      fieldName: "file",
      url: '/api/upload', // 图片上传的接口路径
      //extraData: props.extraData, // 要携带的额外的formData参数
      headers: {
        Authorization: token.value, // 用户身份信息
      },
      filename(name) {  // 过滤特殊字符
        return name
          .replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, "")
          .replace(/[\?\\/:|<>\*\[\]\(\)\$%\{\}@~]/g, "")
          .replace("/\\s/g", "");
      },
      // 粘贴图片的情况下上传的接口路径
      linkToImgUrl: '/api/upload',
      max: 20 * 1024 * 1024,
      multiple: false,
      withCredentials: false,
      // 图片上传校验，可以校验图片大小及类型
      validate(files) {
        const isLt2M = files[0].size / 1024 / 1024 < 20;
        if (!isLt2M) {
            ElMessage.error("上传图片大小不能超过 20MB!");
          return false;
        }
        if (!files[0].type.includes("image")) {
            ElMessage.error("上传图片格式不正确!");
          return false;
        }
        return true;
      },
      //粘贴图片回显处理，如果有图片加了防盗链，则让后台代理替换成自己的图片
      linkToImgFormat(responseText) {
        let res = JSON.parse(responseText);
        if (res.code !== 1) return;
        let end = JSON.stringify({
          msg: "",
          code: 0,
          data: {
            originalURL: res.data,
            url: res.data,
          },
        });
        return end;
      },
      format(files, responseText) {
        console.log(files, responseText);
        
        var res = JSON.parse(responseText);
        if (res.code !== 1) return;
        //图片回显
        // nextTick(() => {
        //   emits("setHtml", getValue(), getHTML());
        // });
        return JSON.stringify({
          msg: "",
          code: 0,
          data: {
            errFiles: [],
            succMap: {
              [files[0].name]: res.data, // 图片上传后的地址
            },
          },
        });
      },
    },
  });
});

//获取token
const getToken = () => {
  const User = JSON.parse(localStorage.getItem("token"));
  if (User && User.token) {
    token.value = User.token;
  }
};

//上传图片
const imageUrl = ref("");

const handleAvatarSuccess = (response) => {
  if (response && response.code === 1) {
    imageUrl.value = response.data;
    form.value.image = response.data;
    ElMessage.success("上传成功");
  } else {
    ElMessage.error(response.msg);
  }
};

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("只支持上传JPG和PNG格式的图片");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error("只能上传小于10MB的图片");
    return false;
  }
  return true;
};
</script>

<template>
  <el-form :model="form" label-width="auto" style="max-width: 100%">
    <el-row>
        <el-col :span="8">
            <el-form-item label="标题：">
        <el-input v-model="form.title" placeholder="请输入标题" />
      </el-form-item>
        </el-col>
      
<el-col :span="16">
    <el-form-item style="display: flex; justify-content: flex-end">
        <el-button style="position: absolute; right: 100px;" type="primary" @click="onSubmit">Create</el-button>
        <el-button style="position: absolute; right: 10px;" @click="cancel">Cancel</el-button>
      </el-form-item>
</el-col>
      
    </el-row>

    <el-row>
      <el-col :span="2">
        <span>图标：</span>
      </el-col>
      <el-col :span="12">
        <el-upload
          class="avatar-uploader"
          action="/api/upload"
          :headers="{ 'token': token }"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-col>
    </el-row>

    <div id="vditor"></div>
  </el-form>
</template>

<style scoped>


.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
